﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace wordroid.utils.http {
    public class PostClient {
        public PostClient(string parameters) {
                _postData.Append(parameters);
            }

        public PostClient(IList<string> parameters) {
                foreach (var element in parameters) {
                    _postData.Append(string.Format("{0}&", element));
                }
            }

            public PostClient(IDictionary<string, object> parameters) {
                foreach (var pair in parameters) {
                    _postData.Append(string.Format("{0}={1}&", pair.Key, pair.Value));
                }
            }

            public void DownloadStringAsync(Uri address) {
                HttpWebRequest request;

                try {
                    request = (HttpWebRequest)WebRequest.Create(address);
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
                    request.BeginGetRequestStream(RequestReady, request);
                } catch {
                    if (DownloadStringCompleted != null) {
                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate {
                            DownloadStringCompleted(this, new DownloadStringCompletedEventArgs(new NetworkException()));
                        });
                    }
                }
            }

            void RequestReady(IAsyncResult asyncResult) {
                HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;

                using (Stream stream = request.EndGetRequestStream(asyncResult)) {
                    using (StreamWriter writer = new StreamWriter(stream)) {
                        writer.Write(_postData.ToString());
                        writer.Flush();
                    }
                }

                request.BeginGetResponse(ResponseReady, request);
            }

            void ResponseReady(IAsyncResult asyncResult) {
                HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
                HttpWebResponse response = null;

                try {
                    response = (HttpWebResponse)request.EndGetResponse(asyncResult);

                    string result = string.Empty;
                    using (Stream responseStream = response.GetResponseStream()) {
                        using (StreamReader reader = new StreamReader(responseStream)) {
                            result = reader.ReadToEnd();
                        }
                    }

                    if (DownloadStringCompleted != null) {
                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate {
                            DownloadStringCompleted(this, new DownloadStringCompletedEventArgs(result));
                        });
                    }
                } catch {
                    if (DownloadStringCompleted != null) {
                        System.Windows.Deployment.Current.Dispatcher.BeginInvoke(delegate {
                            DownloadStringCompleted(this, new DownloadStringCompletedEventArgs(new NetworkException()));
                        });
                    }
                }
            }

        readonly StringBuilder _postData = new StringBuilder();
         public delegate void DownloadStringCompletedHandler(object sender, DownloadStringCompletedEventArgs e);
         public event DownloadStringCompletedHandler DownloadStringCompleted;
    }

    public class DownloadStringCompletedEventArgs : EventArgs {
        public string Result { get; private set; }

        public Exception Error { get; private set; }

        public DownloadStringCompletedEventArgs(string result) {
            Result = result;
        }

        public DownloadStringCompletedEventArgs(Exception ex) {
            Error = ex;
        }
    }
}